package com.evaluity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.evaluity.bbdd.DBLogin;
import com.evaluity.managers.HttpClientManager;
import com.evaluity.managers.HttpClientManager.OnExecuteHttpPostAsyncListener;

import android.app.Activity;
import android.database.Cursor;
import android.view.View;

public class Usuario {
	 
	 private String Name = "";
	 private String Email = "";
	 private String UID = "";
	 
	    private static String KEY_SUCCESS = "success";
	    private static String KEY_UID = "id_usuario";
	    private static String KEY_NAME = "nombre";
	    private static String KEY_SURNAME = "apellidos";
	    private static String KEY_EMAIL = "mail";
	    private static String KEY_CREATED_AT = "fecha_hora";
	    private static String KEY_USER = "mail";
	    private static String NEW_USER = "newuser";

	 private static String loginURL = "http://unitest.net46.net/index.php/api/login";
	   
	    
	    private Activity activity;
	 

	    public void login(Activity activity, String email, String password){
	     this.activity = activity;
	     HttpClientManager httpclient = new HttpClientManager(activity);
	     httpclient.addNameValue("email", email);
	     httpclient.addNameValue("password", password);
	     

	     httpclient.setOnExecuteHttpPostAsyncListener(new OnExecuteHttpPostAsyncListener() {
	    	 
	   public void onExecuteHttpPostAsyncListener(String ResponseBody) {
		   //System.out.println(ResponseBody);
	    try {   
	     JSONArray jsonArray = new JSONArray(ResponseBody);	
	     JSONObject json = jsonArray.getJSONObject(0);
	     
	     if (json.getString(KEY_SUCCESS) != null) {
	      if((Integer.parseInt(json.getString(KEY_SUCCESS)) == 1)){   
	    	  //System.out.println("Es success 1");
	    	  
	       if(Usuario.this.saveLogin(Usuario.this.activity, json))
	    	   //If user and password corrects
	    	   ListenerLoginUsuario.onLoginCorrect(json, "Login correcto");
	       else
	    	   //if user exist
	    	   
	    	ListenerLoginUsuario.onUserExistDisplayPassField();
	        ListenerLoginUsuario.onLoginWrong("And now the password...");       
	      } else {
	    	  //If user doesn't exist
	    	  //If user and password doesn't match
	    if(Integer.parseInt(json.getString(NEW_USER)) == 1){
	       ListenerLoginUsuario.onLoginWrong("Welcome new user!");
	       //Safe and jump to main
	    } else {
	       ListenerLoginUsuario.onLoginWrong("Incorrect password.");
	    }
	       
	      
	      }
	     } else{
	      ListenerLoginUsuario.onLoginWrong("Technical problems, try again.");  
	      
	     }     
	    } catch (JSONException e) {
	     ListenerLoginUsuario.onLoginWrong("Login incorrecto");  
	    
	    }
	   }

	   public void onErrorHttpPostAsyncListener(String message) {
	   }   
	  });
	     
	     httpclient.executeHttpPost(loginURL);
	    } 
	    
	 
	 private boolean saveLogin(Activity activity, JSONObject json){
	  boolean save = false;
	  this.logout(activity);
	  //System.out.println("login");
	  try {
	   //JSONObject user = json.getJSONObject(KEY_USER);
	   System.out.println("login");
	  
	   DBLogin dblogin = new DBLogin(activity);
	   dblogin.addUser(json.getString(KEY_NAME), json.getString(KEY_EMAIL), json.getString(KEY_UID), json.getString(KEY_CREATED_AT));
	   dblogin.close();
	   save = true;   
	  } catch (JSONException e) {}    
	  return save;
	 }
	 

	 public void logout(Activity activity){
	  DBLogin dblogin = new DBLogin(activity);
	  dblogin.resetTables();
	  dblogin.close();
	 } 
	 

	    public boolean isUserLoggedIn(Activity activity){
	        DBLogin db = new DBLogin(activity);
	        int count = db.getRowCount();
	        db.close();
	        if(count > 0){
	            // user logged in
	            return true;
	        }
	        return false;
	    }
	    
	    public void readUser(Activity activity){
	     DBLogin dblogin = new DBLogin(activity);
	     Cursor cursor = dblogin.getCursorUsuario();
	     if(cursor.moveToNext()){
	      this.setName(cursor.getString(0));
	      this.setEmail(cursor.getString(1));
	      this.setUID(cursor.getString(2));
	     }
	     cursor.close();
	     dblogin.close();
	     
	    }
	 
	 public interface OnRegisterUsuario{
	  void onRegisterFinish(JSONObject json, String msg);
	  void onRegisterException(Exception e, String msg);
	  void onRegisterFail(String msg);
	 } 
	 
	 public interface OnLoginUsuario{
	  void onLoginCorrect(JSONObject json, String msg);
	  void onLoginWrong(String msg);
	  void onUserExistDisplayPassField();
	 }
	 private OnLoginUsuario ListenerLoginUsuario;
	 public void setOnLoginUsuario(OnLoginUsuario l){ListenerLoginUsuario = l;}

	 public String getName() {return Name;}
	 public void setName(String name) {Name = name;}
	 public String getEmail() {return Email;}
	 public void setEmail(String email) {Email = email;}
	 public String getUID() {return UID;}
	 public void setUID(String uID) {UID = uID;}
	 
	}
